import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useLoadingStore = defineStore('loading', () => {
  // 全局加载状态
  const globalLoading = ref(false)
  const loadingTitle = ref('加载中...')
  const loadingSubtitle = ref('')
  const loadingProgress = ref(0)
  const showProgress = ref(false)
  const animationType = ref('medical')
  const loadingTips = ref([])
  const showCancel = ref(false)
  const background = ref('blur')
  
  // 页面级加载状态
  const pageLoadings = ref(new Map())
  
  // 组件级加载状态
  const componentLoadings = ref(new Map())
  
  // API请求加载状态
  const apiLoadings = ref(new Map())
  
  // 计算属性
  const hasAnyLoading = computed(() => {
    return globalLoading.value || 
           pageLoadings.value.size > 0 || 
           componentLoadings.value.size > 0 ||
           apiLoadings.value.size > 0
  })
  
  const activeLoadingsCount = computed(() => {
    return pageLoadings.value.size + componentLoadings.value.size + apiLoadings.value.size
  })
  
  // 全局加载控制
  function showGlobalLoading(options = {}) {
    const {
      title = '加载中...',
      subtitle = '',
      progress = 0,
      showProgressBar = false,
      animation = 'medical',
      tips = [],
      allowCancel = false,
      backgroundType = 'blur'
    } = options
    
    loadingTitle.value = title
    loadingSubtitle.value = subtitle
    loadingProgress.value = progress
    showProgress.value = showProgressBar
    animationType.value = animation
    loadingTips.value = tips
    showCancel.value = allowCancel
    background.value = backgroundType
    globalLoading.value = true
  }
  
  function hideGlobalLoading() {
    globalLoading.value = false
    // 重置状态
    loadingTitle.value = '加载中...'
    loadingSubtitle.value = ''
    loadingProgress.value = 0
    showProgress.value = false
    loadingTips.value = []
    showCancel.value = false
  }
  
  function updateGlobalProgress(progress) {
    loadingProgress.value = Math.max(0, Math.min(100, progress))
  }
  
  function updateGlobalTitle(title) {
    loadingTitle.value = title
  }
  
  function updateGlobalSubtitle(subtitle) {
    loadingSubtitle.value = subtitle
  }
  
  function updateGlobalTips(tips) {
    loadingTips.value = Array.isArray(tips) ? tips : [tips]
  }
  
  // 页面级加载控制
  function showPageLoading(pageId, options = {}) {
    const loadingInfo = {
      id: pageId,
      title: options.title || '页面加载中...',
      startTime: Date.now(),
      ...options
    }
    pageLoadings.value.set(pageId, loadingInfo)
  }
  
  function hidePageLoading(pageId) {
    pageLoadings.value.delete(pageId)
  }
  
  function getPageLoading(pageId) {
    return pageLoadings.value.get(pageId)
  }
  
  // 组件级加载控制
  function showComponentLoading(componentId, options = {}) {
    const loadingInfo = {
      id: componentId,
      title: options.title || '组件加载中...',
      startTime: Date.now(),
      ...options
    }
    componentLoadings.value.set(componentId, loadingInfo)
  }
  
  function hideComponentLoading(componentId) {
    componentLoadings.value.delete(componentId)
  }
  
  function getComponentLoading(componentId) {
    return componentLoadings.value.get(componentId)
  }
  
  // API请求加载控制
  function showApiLoading(apiId, options = {}) {
    const loadingInfo = {
      id: apiId,
      url: options.url || '',
      method: options.method || 'GET',
      title: options.title || '请求处理中...',
      startTime: Date.now(),
      timeout: options.timeout || 30000,
      ...options
    }
    apiLoadings.value.set(apiId, loadingInfo)
    
    // 设置超时
    if (loadingInfo.timeout > 0) {
      setTimeout(() => {
        if (apiLoadings.value.has(apiId)) {
          console.warn(`API请求超时: ${apiId}`)
          hideApiLoading(apiId)
        }
      }, loadingInfo.timeout)
    }
  }
  
  function hideApiLoading(apiId) {
    apiLoadings.value.delete(apiId)
  }
  
  function getApiLoading(apiId) {
    return apiLoadings.value.get(apiId)
  }
  
  // 批量操作
  function hideAllPageLoadings() {
    pageLoadings.value.clear()
  }
  
  function hideAllComponentLoadings() {
    componentLoadings.value.clear()
  }
  
  function hideAllApiLoadings() {
    apiLoadings.value.clear()
  }
  
  function hideAllLoadings() {
    hideGlobalLoading()
    hideAllPageLoadings()
    hideAllComponentLoadings()
    hideAllApiLoadings()
  }
  
  // 获取加载统计信息
  function getLoadingStats() {
    const now = Date.now()
    const stats = {
      global: globalLoading.value,
      pages: Array.from(pageLoadings.value.values()).map(loading => ({
        ...loading,
        duration: now - loading.startTime
      })),
      components: Array.from(componentLoadings.value.values()).map(loading => ({
        ...loading,
        duration: now - loading.startTime
      })),
      apis: Array.from(apiLoadings.value.values()).map(loading => ({
        ...loading,
        duration: now - loading.startTime
      })),
      total: activeLoadingsCount.value
    }
    return stats
  }
  
  // 智能加载管理
  function withLoading(asyncFn, options = {}) {
    const {
      type = 'global',
      id = `loading_${Date.now()}`,
      title = '处理中...',
      showProgressBar = false,
      minDuration = 500
    } = options
    
    return async (...args) => {
      const startTime = Date.now()
      
      try {
        // 显示加载
        switch (type) {
          case 'global':
            showGlobalLoading({ title, showProgressBar, ...options })
            break
          case 'page':
            showPageLoading(id, { title, ...options })
            break
          case 'component':
            showComponentLoading(id, { title, ...options })
            break
          case 'api':
            showApiLoading(id, { title, ...options })
            break
        }
        
        // 执行异步函数
        const result = await asyncFn(...args)
        
        // 确保最小显示时间
        const elapsed = Date.now() - startTime
        if (elapsed < minDuration) {
          await new Promise(resolve => setTimeout(resolve, minDuration - elapsed))
        }
        
        return result
      } finally {
        // 隐藏加载
        switch (type) {
          case 'global':
            hideGlobalLoading()
            break
          case 'page':
            hidePageLoading(id)
            break
          case 'component':
            hideComponentLoading(id)
            break
          case 'api':
            hideApiLoading(id)
            break
        }
      }
    }
  }
  
  // 进度管理
  function createProgressManager(total = 100) {
    let current = 0
    
    return {
      increment(step = 1) {
        current = Math.min(total, current + step)
        updateGlobalProgress((current / total) * 100)
        return current
      },
      
      setProgress(value) {
        current = Math.max(0, Math.min(total, value))
        updateGlobalProgress((current / total) * 100)
        return current
      },
      
      complete() {
        current = total
        updateGlobalProgress(100)
        return current
      },
      
      reset() {
        current = 0
        updateGlobalProgress(0)
        return current
      },
      
      get current() {
        return current
      },
      
      get total() {
        return total
      },
      
      get percentage() {
        return (current / total) * 100
      }
    }
  }
  
  // 预设加载配置
  const presets = {
    // 数据加载
    dataLoading: {
      title: '数据加载中...',
      animation: 'spinner',
      tips: ['正在获取数据...', '请稍候...'],
      background: 'blur'
    },
    
    // 文件上传
    fileUpload: {
      title: '文件上传中...',
      animation: 'wave',
      showProgressBar: true,
      tips: ['正在上传文件...', '请勿关闭页面...'],
      allowCancel: true
    },
    
    // 页面切换
    pageTransition: {
      title: '页面加载中...',
      animation: 'pulse',
      background: 'light',
      minDuration: 300
    },
    
    // 医疗数据处理
    medicalProcessing: {
      title: '医疗数据处理中...',
      animation: 'medical',
      tips: ['正在分析数据...', '生成报告中...', '即将完成...'],
      background: 'blur'
    },
    
    // 登录验证
    authentication: {
      title: '身份验证中...',
      animation: 'spinner',
      tips: ['正在验证身份...', '请稍候...'],
      background: 'dark'
    }
  }
  
  function showPresetLoading(presetName, customOptions = {}) {
    const preset = presets[presetName]
    if (!preset) {
      console.warn(`未找到预设加载配置: ${presetName}`)
      return showGlobalLoading(customOptions)
    }
    
    showGlobalLoading({ ...preset, ...customOptions })
  }
  
  return {
    // 状态
    globalLoading,
    loadingTitle,
    loadingSubtitle,
    loadingProgress,
    showProgress,
    animationType,
    loadingTips,
    showCancel,
    background,
    hasAnyLoading,
    activeLoadingsCount,
    
    // 全局加载控制
    showGlobalLoading,
    hideGlobalLoading,
    updateGlobalProgress,
    updateGlobalTitle,
    updateGlobalSubtitle,
    updateGlobalTips,
    
    // 页面级加载控制
    showPageLoading,
    hidePageLoading,
    getPageLoading,
    
    // 组件级加载控制
    showComponentLoading,
    hideComponentLoading,
    getComponentLoading,
    
    // API请求加载控制
    showApiLoading,
    hideApiLoading,
    getApiLoading,
    
    // 批量操作
    hideAllPageLoadings,
    hideAllComponentLoadings,
    hideAllApiLoadings,
    hideAllLoadings,
    
    // 工具方法
    getLoadingStats,
    withLoading,
    createProgressManager,
    showPresetLoading,
    
    // 预设配置
    presets
  }
})